<template>
  <view class="cmt-view">
    <!-- 提示信息弹窗 -->
    <uni-popup ref="message" type="message">
      <uni-popup-message :type="data.msgType" :message="data.messageText" :duration="2000"></uni-popup-message>
    </uni-popup>
    <scroll-view scroll-y="true" style="width: 100vw;height: 93vh;" lower-threshold="50" @scrolltolower="getMoreCmtMsg">
      <!-- 点赞评论 -->
      <view class="cmt-item"v-for="(item,index) in data.cmtMsg" :key="index">
        <view class="cmt-info">
          <image class="avatar" lazy-load="true" :src="item.userAvatar" @click.stop="showOtherInfo(item.userId)"></image>
            <view class="cmt-content">
              <text class="user-name">{{item.userName}}</text>
              <view>
                <text class="act-text">{{item.tag}}</text>
                <text class="time">{{item.time}}</text>
              </view>
              <text class="content-text">{{item.content}}</text>
            </view>
            <image class="note-cover" lazy-load="true" :src="item.cover" @click="showNote(item.noteId)"></image>
          </view>
          <!-- 点赞和回复 -->
          <view class="cmt-act-box">
            <view class="cmt-act-item" @click.stop="likeCmt(index)">
              <image v-if="item.like > 0" class="cmt-act-img" src="../../static/img/like-btn2.png"></image>
                  
              <image v-else class="cmt-act-img" src="../../static/img/like-btn1.png"></image>
              <text v-if="item.likeNum > 0">{{item.likeNum}}</text>
              <text v-else>点赞</text>
            </view>
            <view class="cmt-act-item" @click.stop="replyCmt(index)">
              <image class="cmt-act-img" src="../../static/img/comment-btn1.png"></image>
              <text>回复</text>
            </view>
          </view>
        </view>
    </scroll-view>
    
    
    <!-- 底部发表评论或点赞 -->
    <view class="comment-view" v-if="data.focus" :style="{ bottom: data.bottomValue + 'px' }">
      <view style="display: flex;align-items: center;height: 100%;">
        <view class="comment-input">
          <input v-model="data.msg" class="c-input" type="text" @blur="changeFocus" @focus="inputFocus" :focus="data.focus" @confirm="sendMsg" :placeholder="data.placeholder" :adjust-position="false"/>
        </view>        
      </view>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,onMounted } from 'vue';
import { onShow,onLoad,onUnload,onHide } from '@dcloudio/uni-app'
import helper from '../../common/helper.js'

const data = reactive({
  cmtMsg:[],
  total:0,
  pageNum:0,
  pageSize:10,
  msg:"",
  focus: false,
  placeholder:"说点什么",
  index: "",
  msgType:"",
  messageText:"",
  bottomValue: 0
});

const message = ref(null)

function messageToggle(type,text) {
  data.msgType = type
  data.messageText = text
  message.value.open()
}

onLoad(()=>{
  getCmtMsg()
})

function getCmtMsg(){
  uni.request({
    url: helper.webUrl + "/comment/getCmtMsg",
    method:'GET',
    header:{
      'Content-Type': 'application/x-www-form-urlencoded',
      'token': helper.getToken()
    },
    data: {
      pageNum: data.pageNum,
      pageSize: data.pageSize
    },
    success: (res) => {
      console.log(res.data);
      if(res.data.code == 200){
        data.total = res.data.data.total
        let list = res.data.data.record
        for(let i = 0; i < list.length; i++){
          list[i].time = helper.getDate(list[i].time)
          data.cmtMsg.push(list[i])
        }
        data.pageNum++
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  })
}

function getMoreCmtMsg(){
  console.log("获取更多的评论信息")
  if(data.total > data.cmtMsg.length){
    getCmtMsg()
  }
}

function showNote(noteId){
  console.log("查看笔记"+noteId)
  let index = ""
  uni.navigateTo({
    url:`/subpages/noteDetail/noteDetail?noteId=${noteId}&index=${index}`
  })
}
function showOtherInfo(userId){
  console.log("查看用户")
  uni.navigateTo({
    url:"/subpages/otherInfo/otherInfo?userId="+userId
  })
}

function likeCmtReq(commentId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/comment/likeCmt",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': helper.getToken()
      },
      data: {
        userId: helper.getUserId(),
        commentId: commentId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
}
function dislikeCmtReq(commentId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/comment/dislikeCmt",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': helper.getToken()
      },
      data: {
        userId: helper.getUserId(),
        commentId: commentId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
}

function likeReplyReq(replyId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/reply/likeReply",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': helper.getToken()
      },
      data: {
        userId: helper.getUserId(),
        replyId: replyId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
}
function dislikeReplyReq(replyId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/reply/dislikeReply",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': helper.getToken()
      },
      data: {
        userId: helper.getUserId(),
        replyId: replyId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
}

async function likeCmt(index){
  console.log("点赞评论")
  if(data.cmtMsg[index].tag == "评论了你的笔记"){
    if(data.cmtMsg[index].like > 0){
      let res = await dislikeCmtReq(data.cmtMsg[index].cId)
      if(res.data.code == 200){
        data.cmtMsg[index].like = 0
        data.cmtMsg[index].likeNum--
      }
    }else{
      let res = await likeCmtReq(data.cmtMsg[index].cId)
      if(res.data.code == 200){
        data.cmtMsg[index].like = 1
        data.cmtMsg[index].likeNum++
      }
    }
  }else{
    if(data.cmtMsg[index].like > 0){
      let res = await dislikeReplyReq(data.cmtMsg[index].id)
      if(res.data.code == 200){
        data.cmtMsg[index].like = 0
        data.cmtMsg[index].likeNum--
      }
    }else{
      let res = await likeReplyReq(data.cmtMsg[index].id)
      if(res.data.code == 200){
        data.cmtMsg[index].like = 1
        data.cmtMsg[index].likeNum++
      }
    }
  }
}

function replyCmtReq(commentId,msg,replyId){
  return new Promise((resolve, reject) => {
    uni.request({
      url: helper.webUrl + "/reply/addReply",
      method:'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: helper.getUserId(),
        commentId: commentId,
        content: msg,
        replyId: replyId
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });  
}

function changeFocus(e){
  console.log("修改focus值")
  data.focus = false
  data.placeholder = "说点什么..."
  data.index = ""
  data.msg = ""
  //修改输入的盒子的bottom值
  data.bottomValue = 0
}

function inputFocus(e){
  //修改输入的盒子的bottom值
  data.bottomValue = e.detail.height
}

function replyCmt(index){
  data.focus = true
  data.placeholder = "回复："+data.cmtMsg[index].userName
  data.index = index
}
async function sendMsg(){
  if(data.cmtMsg[data.index].tag == "评论了你的笔记"){
    console.log("回复评论")
    let res = await replyCmtReq(data.cmtMsg[data.index].cId,data.msg,"")
    if(res.data.code == 200){
      messageToggle("success","回复成功！")
    }
  }else{
    console.log("回复回复")
    let res = await replyCmtReq(data.cmtMsg[data.index].cId,data.msg,data.cmtMsg[data.index].id)
    if(res.data.code == 200){
      messageToggle("success","回复成功！")
    }
  }
}
</script>

<style>
.cmt-view{
  width: 100vw;
  height: 100vh;
}
.cmt-item{
  width: 100vw;
  padding-bottom: 10px;
  background-color: #fff;
  border-bottom: 1px solid #c5c5c5;
}
.cmt-info{
  display: flex;
  width: 100vw;
  min-height: 15vh;
  align-items: center;
  background-color: #fff;
  padding-block: 5px;
}
.avatar{
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-left: 20px;
}
.cmt-content{
  display: flex;
  flex-direction: column;
  width: 60%;
  margin-left: 10px;
}
.user-name{
  font-size: 16px;
}
.act-text{
  font-size: 14px;
  color: #949494;
}
.content-text{
  font-size: 13px;
}
.time{
  margin-left: 10px;
}
.note-cover{
  width: 60px;
  height: 60px;
  border-radius: 20%;
  margin-left: auto;
  margin-right: 20px;
}
.cmt-box{
  display: flex;
  margin-top: 5px;
}
.cmt-index{
  width:5px;
  height: 20px;
  background-color: #949494;
}
.cmt-text{
  margin-left: 10px;
  font-size: 12px;
  color: #949494;
}
.cmt-act-box{
  display: flex;
  margin-left: 15vw;
}
.cmt-act-item{
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f4f4f4;
  border-radius: 50px;
  margin-left: 10px;
}
.cmt-act-img{
  width: 25px;
  height: 25px;
}
.comment-view{
  position: absolute;
  bottom: 0;
  align-items: center;
  width: 100vw;
  height: 7vh;
  border-top: 1px solid #aaaaaa;
  background-color: #fff;
}
.comment-input{
  width: 95%;
  height: 60%;
  margin: auto;
  display: flex;
  border-radius: 15px;
  background-color: #f4f4f4;
}
.c-input{
  margin-left: 5%;
  width: 100%;
  height: 100%;
  font-size: 14px;
}
</style>
